#!/usr/bin/env python
# --*-- coding: UTF-8 --*--
import sys, time
import locale
import poplib
from email import parser
import email
import string
import getpass;

# 确定运行环境的encoding
__g_codeset = sys.getdefaultencoding()
if "ascii"==__g_codeset:
    __g_codeset = locale.getdefaultlocale()[1]
#

def object2double(obj):
    if(obj==None or obj==""):
        return 0
    else:
        return float(obj)
    #end if
#

def utf8_to_mbs(s):
    return s.decode("utf-8").encode(__g_codeset)
#

def mbs_to_utf8(s):
    return s.decode(__g_codeset).encode("utf-8")
#

def getCache():
    file = open("cache", 'r');
    value = file.readline();
    file.close();
    return value;

def setCache(value):
    output = open("cache", 'w');
    output.write(value);
    output.close();

def parseMessage(message, oldTime):
    message = parser.Parser().parsestr("\n".join(message[1]));
    subject = message.get('subject')
    h = email.Header.Header(subject)
    dh = email.Header.decode_header(h)
    # 邮件主题
    subject = unicode(dh[0][0], dh[0][1]).encode('utf8')
    mTime = message.get("Date");
    mTime = time.mktime(time.strptime(mTime, "%a, %d %b %Y %H:%M:%S +0800"))

    if(mTime <= oldTime):
        return -1;

    maxTime = int(getCache());

    if(maxTime < mTime):
        setCache("%d" % (mTime));

    print("%d" % (mTime));
    return 1;

def test(host, username, password):
    # 上次便利是最新的邮件时间。
    oldTime = int(getCache());

    # mail = poplib.POP3("pop3.mxhichina.com");
    mail = poplib.POP3_SSL(host);
    mail.user(username);
    mail.pass_(password);
    # 获得邮件
    messages = mail.list()[1]
    number = len(messages)
    print(">>> %d" % (number))
    parseMessage(mail.retr(number - 1), oldTime)
    # mail.dele(number - 1)
    mail.quit()

def mail(host, username, password):
    # mail = poplib.POP3("pop3.mxhichina.com");
    mail = poplib.POP3_SSL(host);
    mail.user(username);
    mail.pass_(password);
    # 获得邮件
    # pop_conn
    messages = [mail.retr(i) for i in range(1, len(mail.list()[1]) + 1)]
    messages = ["\n".join(mssg[1]) for mssg in messages]
    messages = [parser.Parser().parsestr(mssg) for mssg in messages]

host = 'pop3.mxhichina.com';
username = 'yandong@zxianstudio.com';
password = 'Zxianyun123';
test(host, username, password)
